<template>
  <div class="logStatistics">
    <a-tabs v-model:activeKey="editActiveKey">
      <div class="logStatistics-header">
        <div class="logStatistics-header-left">
          <span>统计维度：</span>
          <a-select
            v-model:value="timeType"
            style="width: 120px"
            :options="timeTypeOptions"
            :style="{ width: '112px' }"
            @select="getLogData()"
          >
          </a-select>

          <div class="time">
            <span>统计时间：</span>

            <date-range-picker
              v-model:value="selectTimeRange"
              :valueFormat="valueFormat"
              :showTime="false"
              :disabled="+timeType == 1"
              :disabledInfo="disabledInfo"
              @change="getLogData()"
            ></date-range-picker>
          </div>
        </div>
        <div class="searchName" v-if="editActiveKey == 4">
          <a-input
            v-model:value="searchUserName"
            placeholder="请输入用户名称"
            style="width: 192px; height: 32px"
          >
            <template #suffix>
              <i class="iconfont icon-search" @click="getLogData()"></i>
            </template>
          </a-input>
        </div>
      </div>
      <a-tab-pane key="1" tab="操作类型" :forceRender="true">
        <div class="a-scroll">
          <div id="fetchStatisticsOperateTypeLogList" class="canvas"></div>
        </div>
      </a-tab-pane>
      <a-tab-pane key="2" tab="事件类型" :forceRender="true">
        <div id="a-scroll" class="a-scroll">
          <div id="fetchStatisticsEventTypeLogList" class="canvas"></div>
        </div>
      </a-tab-pane>
      <a-tab-pane key="3" tab="操作结果" :forceRender="true">
        <div class="a-scroll">
          <div id="fetchStatisticsResultLogList" class="canvas"></div>
        </div>
      </a-tab-pane>
      <a-tab-pane key="4" tab="用户日志" :forceRender="true">
        <div class="a-scroll">
          <div id="fetchStatisticsUserNameTypeLogList" class="canvas"></div>
        </div>
      </a-tab-pane>
    </a-tabs>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted, nextTick, watch } from "vue";
import dateRangePicker from "@/components/picker/dateRangePicker.vue";
import { initEcharts } from "@/components/echarts/index";
import { optionBar } from "./echartType/options";
import request from "@/api/index";

// TS
interface dataSourceType {
  [propName: string]: any;
}
//data
//tab页签相关数据
const editActiveKey = ref<string | number>("1");
//筛选头部
const timeType = ref<String | boolean>("1"); // 筛选过滤表格数据
const timeTypeOptions = ref<dataSourceType["options"]>([
  // 应用场景
  {
    value: "1",
    label: "小时统计",
  },
  {
    value: "2",
    label: "天统计",
  },
  {
    value: "3",
    label: "月统计",
  },
  {
    value: "4",
    label: "年统计",
  },
]);
const valueFormat = ref("YYYY-MM-DD");
const selectTimeRange = ref<(string | number)[]>([]); //选择时间范围
const disabledInfo = reactive({
  //日期禁选
  type: 2,
  startDays: 0,
});
const searchUserName = ref(""); // 搜索用户名
// api
const apiList = ref([
  "fetchStatisticsOperateTypeLogList",
  "fetchStatisticsEventTypeLogList",
  "fetchStatisticsResultLogList",
  "fetchStatisticsUserNameTypeLogList",
]);
//日志数据
const logData = ref(JSON.parse(JSON.stringify(optionBar)));

//wacth
watch(
  () => editActiveKey.value,
  (newVal, oldVal) => {
    // 防止echart在切换tab时找不到容器宽度，即容器这时是display:none
    if (newVal != oldVal) {
      //

      nextTick(() => {
        if (newVal == 4) {
          timeType.value = true;
          timeTypeOptions.value = [
            {
              value: true,
              label: "今日统计",
            },
            {
              value: false,
              label: "历史统计",
            },
          ];
        } else {
          timeType.value = "1";
          timeTypeOptions.value = [
            {
              value: "1",
              label: "小时统计",
            },
            {
              value: "2",
              label: "天统计",
            },
            {
              value: "3",
              label: "月统计",
            },
            {
              value: "4",
              label: "年统计",
            },
          ];
        }
        selectTimeRange.value = [];
        searchUserName.value = "";
        getLogData(newVal);
      });
    }
  }
);
//methods:
const getLogData = (key: string | number = "") => {
  nextTick(() => {
    logData.value = JSON.parse(JSON.stringify(optionBar));
    let params = {
      cycle: timeType.value,
      endTime: selectTimeRange.value[1] || null,
      startTime: selectTimeRange.value[0] || null,
      userName: searchUserName.value,
      today: timeType.value,
    };
    request[apiList.value[key ? +key - 1 : +editActiveKey.value - 1]](
      params
    ).then((res: dataSourceType) => {
      dealData(res, apiList.value[key ? +key - 1 : +editActiveKey.value - 1]);
    });
  });
};
//处理后台返回的数据
const dealData = (data: dataSourceType, id: string) => {
  let xAxis: (string | number)[] = [];
  let series: dataSourceType[] = [];
  if (data.name) {
    //一般格式
    let nameKeyList = Object.keys(data.name);
    let nameValueList = Object.values(data.name);
    for (let i of nameKeyList) {
      if (!xAxis.length) {
        if (Object.keys(data[i]).length) {
          xAxis = Object.keys(data[i]).sort((a: any, b: any) => a - b);
        }
      } else {
        continue;
      }
    }
    for (let i of nameKeyList) {
      let obj = {
        name: data.name[i],
        data: [] as (string | number)[],
        type: "bar",
        stack: "Search Engine",
        // emphasis: {
        //   focus: 'series'
        // },
        barMaxWidth: 40,
      };
      for (let j of xAxis) {
        obj.data.push(data[i][j]);
      }
      series.push(obj);
    }

    logData.value.legend.data = JSON.parse(JSON.stringify(nameValueList));
  } else {
    data.forEach((item: dataSourceType) => {
      xAxis.push(item.createUser);
      series.push({
        name: item.createUser,
        data: [item.counts],
        type: "bar",
        barMaxWidth: 40,
      });
    });
    if (!data.length) {
      logData.value.xAxis = [];
      logData.value.yAxis = [];
      initEcharts(id, logData.value);
      return;
    }
  }
  logData.value.xAxis[0].data = JSON.parse(JSON.stringify(xAxis));
  logData.value.series = JSON.parse(JSON.stringify(series));
  initEcharts(id, logData.value);
};

//onMounted
onMounted(() => {
  getLogData();
  //initEcharts('operateType', logData.value);
});
</script>

<style lang="less">
.logStatistics {
  background-color: #fff;
  width: 100%;
  height: calc(100% - 72px);

  .searchName {
    font-size: 14px;
    color: #333;
    margin-left: 16px;
  }

  .ant-tabs-content {
    flex-direction: column;
    height: 100%;

    .logStatistics-header {
      width: 100%;
      height: 80px;
      display: flex;
      align-items: center;
      padding: 16px;
      justify-content: space-between;

      .logStatistics-header-left {
        display: flex;
        align-items: center;
      }

      .time {
        margin: 0 16px;
      }
    }

    .canvas {
      width: 100% !important;
      height: 600px;
      overflow-y: auto;
    }
  }

  .ant-tabs.ant-tabs-top {
    height: 100%;
    overflow: hidden;

    .ant-tabs-content-holder {
      height: 100%;
      overflow: hidden;

      .ant-tabs-content.ant-tabs-content-top {
        height: 100%;
        overflow: hidden;

        .ant-tabs-tabpane-active {
          height: calc(100%);
          position: relative;
          overflow: hidden;
        }

        .a-scroll {
          height: calc(100% - 80px);
          overflow-y: auto;
        }
      }
    }
  }
}
</style>
